﻿<%@ WebHandler Language="C#" Class="SupplyContainerInStoreVue3PageHandler" %>

/* Description:补充入库后端接口
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.11.26
 */

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Collections;
using System.IO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using BusinessRule.DTO;
using System.Configuration;

public class SupplyContainerInStoreVue3PageHandler : IHttpHandler, IRequiresSessionState
{
    class Result
    {
        public object data { get; set; }
        public Meta meta { get; set; }
        public int total { get; set; }
        public class Meta
        {
            public int status;
            public string msg;
            public Meta(int status, string msg)
            {
                this.status = status;
                this.msg = msg;
            }
        }
    }

    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    BusinessRule.IBusiness.uLMSCommonIBusiness m_Common = BusinessRule.BusinessFactory.uMESBusinessFactory.instance.GetuLMSCommonObject();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getUserInfo":
                        r = getUserInfo();//查询当前用户信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getData":
                        r = getData(jObject);//查询未入库数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getContainerList":
                        r = getContainerList(jObject);//查询未入库批次明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getInstoreToWMSData":
                        r = getInstoreToWMSData(jObject);//查询已入库数据
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getInstoreToWMSDataDetail":
                        r = getInstoreToWMSDataDetail(jObject);//查询已入库批次明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "cancelInstore":
                        r = cancelInstore(jObject);//入库撤销
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getUserInfo()
    {
        Result r = new Result();
        r.data = m_UserInfo;
        r.total = 0;
        r.meta = m_UserInfo == null ? new Result.Meta(500, "当前未登录") : new Result.Meta(200, "请求成功");
        return r;
    }

    //查询未入库数据
    Result getData(JObject jObject)
    {
        string sql = @"
SELECT  m.mfgorderid,c.mfgbatch,NULL containerid,p.description,c.qty,s.specno,m.mfgordername,NULL containername,p.productid,
        c.togetherflag,pb.productname,ws.workflowstepname,ws.workflowstepid,ws.workflowid,ws.sequence,c.containertype,
        DECODE(c.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS containertypename,cfci.acceptanceqty,cfci.lossqty,
        cfci.defectqty,cfci.reworkqty,cfci.createdate ,(NVL(cci.workflowroute,cci.productname)||'/'||cci.containerno) productbatch,
        (cci.productname||'/'||cci.containerno) productbatchhidden     
FROM containerfinishedcheckinfo cfci 
LEFT JOIN container c ON c.containerid=cfci.containerid
LEFT JOIN containercurrentinfo cci ON cci.containerid=c.containerid
LEFT JOIN containerinstore cis ON cis.charg=c.containername AND cis.isuse = 0
LEFT JOIN workflowstep ws ON ws.workflowstepid=cfci.workflowstepid
LEFT JOIN mfgorder m ON m.mfgorderid=c.mfgorderid
LEFT JOIN product p ON p.productid=c.productid
LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
LEFT JOIN specbase sb ON sb.specbaseid=ws.specbaseid
LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,ws.specid)
LEFT JOIN containerfinishedcheckinfo cfci2 ON cfci2.containerid=cfci.containerid
WHERE cfci.isuse=0 AND cis.charg IS NULL AND c.status=1 AND c.containertype!='7'";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cfci.factoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND m.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND c.containername = '{0}'", jObject["containername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND pb.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["specno"] != null && jObject["specno"].ToString() != "")
        {
            sql += string.Format(" AND s.specno LIKE '%{0}%'", jObject["specno"].ToString());
        }

        sql += @"
GROUP BY m.mfgorderid,c.mfgbatch,p.description,c.qty,s.specno,m.mfgordername,  
         c.togetherflag,pb.productname,ws.workflowstepname,ws.workflowstepid,ws.workflowid,ws.sequence,c.containertype,cfci.acceptanceqty,
         cfci.lossqty,cfci.defectqty,cfci.reworkqty,cfci.createdate,cci.containerno,cci.workflowroute,cci.productname,p.productid
HAVING cfci.createdate>=MAX(cfci2.createdate)

UNION ALL
SELECT  m.mfgorderid,NULL mfgbatch, NULL containerid,p.description,SUM(c.qty) qty,s.specno,m.mfgordername,NULL containername,p.productid,
        c.togetherflag,pb.productname,ws.workflowstepname,
        ws.workflowstepid,ws.workflowid,ws.sequence,c.containertype,DECODE(c.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS containertypename,
        SUM(cfci.acceptanceqty) acceptanceqty,SUM(cfci.lossqty) lossqty,SUM(cfci.defectqty) defectqty,SUM(cfci.reworkqty) reworkqty,
        NULL createdate,(NVL(cci.workflowroute,cci.productname)||'/'||cci.containerno) productbatch,(cci.productname||'/'||cci.containerno) productbatchhidden 
FROM containerfinishedcheckinfo cfci 
LEFT JOIN container c ON c.containerid=cfci.containerid
LEFT JOIN containercurrentinfo cci ON cci.containerid=c.containerid
LEFT JOIN containerinstore cis ON cis.charg=c.containername AND cis.isuse = 0
LEFT JOIN workflowstep ws ON ws.workflowstepid=cfci.workflowstepid
LEFT JOIN mfgorder m ON m.mfgorderid=c.mfgorderid
LEFT JOIN product p ON p.productid=c.productid
LEFT JOIN productbase pb ON pb.productbaseid=p.productbaseid
LEFT JOIN specbase sb ON sb.specbaseid=ws.specbaseid
LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,ws.specid)
LEFT JOIN 
( SELECT cfci.containerid,MAX(cfci.createdate) maxcreatedate 
  FROM containerfinishedcheckinfo cfci 
  WHERE cfci.isuse=0 
  GROUP BY cfci.containerid
) a ON
a.containerid=cfci.containerid
WHERE cfci.isuse=0 AND cfci.createdate=a.maxcreatedate AND cis.charg IS NULL AND c.status=1 AND c.containertype='7'";

        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cfci.factoryid = '{0}'", jObject["factoryid"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND m.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND c.containername = '{0}'", jObject["containername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND pb.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["specno"] != null && jObject["specno"].ToString() != "")
        {
            sql += string.Format(" AND s.specno LIKE '%{0}%'", jObject["specno"].ToString());
        }

        sql += @"
GROUP BY m.mfgorderid,p.description,c.qty,s.specno,m.mfgordername,c.togetherflag,pb.productname,ws.workflowstepname,
         ws.workflowstepid,ws.workflowid,ws.sequence,c.containertype,cfci.acceptanceqty,cfci.lossqty,cfci.defectqty,
         cfci.reworkqty,c.togetherflag,cci.containerno,cci.workflowroute,cci.productname,p.productid";

        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(jObject["currentPage"]);//页码
        paraPage.PageSize = Convert.ToInt32(jObject["pageSize"]);//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        DataTable dtResult = result.DBTable;

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(result.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询未入库批次明细
    Result getContainerList(JObject obj)
    {
        string sql = @"
SELECT c.containerid,c.containername,c.mfgbatch,cfci.createdate,e.fullname,c.qty,cci.mfgordername,cci.familylistnames 
FROM containerfinishedcheckinfo cfci
LEFT JOIN container c ON c.containerid=cfci.containerid
LEFT JOIN containercurrentinfo cci ON cci.containerid = cfci.containerid
LEFT JOIN containerinstore cis ON cis.charg=c.containername AND cis.isuse = 0
LEFT JOIN 
( SELECT cfci.containerid,MAX(cfci.createdate) maxcreatedate 
  FROM containerfinishedcheckinfo cfci 
  WHERE cfci.isuse=0 GROUP BY cfci.containerid
) a ON a.containerid=cfci.containerid
LEFT JOIN employee e ON e.employeeid=cfci.checkerid
WHERE cfci.isuse=0 AND cis.charg IS NULL AND c.status=1 AND cis.charg IS NULL AND cfci.createdate=a.maxcreatedate AND c.containertype=7 
      AND cfci.workflowstepid='{0}' 
      AND c.togetherflag='{1}'
      AND c.mfgorderid='{2}' 
      AND cfci.factoryid='{3}' 
UNION ALL
SELECT c.containerid,c.containername,c.mfgbatch,cfci.createdate,e.fullname,c.qty,cci.mfgordername,cci.familylistnames
FROM containerfinishedcheckinfo cfci
LEFT JOIN container c ON c.containerid=cfci.containerid
LEFT JOIN containercurrentinfo cci ON cci.containerid = cfci.containerid
LEFT JOIN containerinstore cis ON cis.charg=c.containername AND cis.isuse = 0
LEFT JOIN 
( SELECT cfci.containerid,MAX(cfci.createdate) maxcreatedate 
  FROM containerfinishedcheckinfo cfci 
  WHERE cfci.isuse=0 
  GROUP BY cfci.containerid
) a ON a.containerid=cfci.containerid
LEFT JOIN employee e ON e.employeeid=cfci.checkerid
WHERE cfci.isuse=0 AND cis.charg IS NULL AND c.status=1 AND cis.charg IS NULL AND cfci.createdate=a.maxcreatedate AND c.containertype!=7
      AND cfci.workflowstepid='{0}' 
      AND c.containername='{1}' 
      AND c.mfgorderid='{2}'
      AND cfci.factoryid='{3}'";

        sql = string.Format(sql, obj["workflowstepid"].ToString(), obj["togetherflag"].ToString(), obj["mfgorderid"].ToString(), obj["factoryid"].ToString());
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询已入库数据
    Result getInstoreToWMSData(JObject obj)
    {
        string sql = @"
SELECT cci.mfgorderid,c.mfgbatch,cci.productdescription description,ws.workflowstepname,s.specno,cci.mfgordername,SUM(c.qty) qty,
       cci.togetherflag,cci.productname,ws.workflowstepid,ws.workflowid,ws.sequence,c.containertype,
       DECODE(c.containertype,2,'批量加工',3,'批量带子序号', 7,'单件加工') AS containertypename,
       SUM(cfci.acceptanceqty) acceptanceqty,SUM(cfci.lossqty) lossqty,SUM(cfci.defectqty) defectqty,SUM(cfci.reworkqty) reworkqty,
       (NVL(cci.workflowroute,cci.productname)||'/'||cci.containerno) productbatch,
       (cci.productname||'/'||cci.containerno) productbatchhidden 
FROM sync_sendto_wms wms
LEFT JOIN containerinstore cid ON cid.containerinstoreid = wms.uniquecolvalue
LEFT JOIN containercurrentinfo cci ON cci.containername = cid.charg
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN containerfinishedcheckinfo cfci ON cfci.containerid = cci.containerid AND cfci.isuse = 0
LEFT JOIN workflowstep ws ON ws.workflowstepid = cfci.workflowstepid
LEFT JOIN specbase sb ON sb.specbaseid= ws.specbaseid
LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,ws.specid)
WHERE wms.ismeshandle = 1 AND wms.isuse = '0' AND wms.methodname = '入库申请'";

        if (obj["factoryid"] != null && obj["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND cfci.factoryid = '{0}'", obj["factoryid"].ToString());
        }

        if (obj["mfgordername"] != null && obj["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND cci.mfgordername = '{0}'", obj["mfgordername"].ToString());
        }

        if (obj["containername"] != null && obj["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername = '{0}'", obj["containername"].ToString());
        }

        if (obj["productname"] != null && obj["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname = '{0}'", obj["productname"].ToString());
        }

        if (obj["specno"] != null && obj["specno"].ToString() != "")
        {
            sql += string.Format(" AND s.specno LIKE '%{0}%'", obj["specno"].ToString());
        }

        sql += @"
GROUP BY cci.mfgorderid,c.mfgbatch,cci.productdescription,ws.workflowstepname,s.specno,cci.mfgordername,
         cci.togetherflag,cci.productname,ws.workflowstepname,ws.workflowstepid,ws.workflowid,ws.sequence,c.containertype,
         cci.workflowroute,cci.productname,cci.containerno";

        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //查询已入库批次明细
    Result getInstoreToWMSDataDetail(JObject obj)
    {
        string sql = @"
SELECT cid.aufnr mfgordername,cid.charg containername,cid.containerinstoreid,cci.containerid,wms.createdate instore_date,e.fullname instore_emp
FROM sync_sendto_wms wms
LEFT JOIN containerinstore cid ON cid.containerinstoreid = wms.uniquecolvalue
LEFT JOIN containercurrentinfo cci ON cci.containername = cid.charg
LEFT JOIN employee e ON e.employeeid = wms.create_emp
WHERE wms.isuse = 0 AND wms.ismeshandle = 1 AND wms.methodname = '入库申请'";

        if (obj["togetherflag"] != null && obj["togetherflag"].ToString() != "")
        {
            sql += string.Format(" AND cci.togetherflag = '{0}'", obj["togetherflag"].ToString());
        }

        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);

        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //入库撤销
    Result cancelInstore(JObject obj)
    {
        DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(obj["postData"].ToString());
        foreach (DataRow dr in dtPostData.Rows)
        {
            //1.将MES入库单表数据设置为无效
            string updateSql = "UPDATE containerinstore cid SET cid.isuse = 1 WHERE cid.containerinstoreid = '{0}'";
            updateSql = string.Format(updateSql, dr["containerinstoreid"].ToString());
            DatabaseHelper.ExecuteSql(updateSql);

            //2.将入库申请记录设置为无效
            string updateSql2 = @"UPDATE sync_sendto_wms t SET t.isuse = 1,t.lastchange_emp='{0}',t.lastchangedate=sysdate WHERE t.uniquecolvalue = '{1}'";
            updateSql2 = String.Format(updateSql2, obj["employeeid"].ToString(), dr["containerinstoreid"].ToString());
            DatabaseHelper.ExecuteSql(updateSql2);

            string sql = @"
SELECT cci.mfgordername,cci.containername,p.materialcode,cci.qty
FROM containercurrentinfo cci
LEFT JOIN product p ON p.productid = cci.productid
WHERE cci.containerid = '{0}'";
            sql = String.Format(sql, dr["containerid"].ToString());

            DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtContainer.Rows.Count > 0)
            {
                Dictionary<string, object> para = new Dictionary<string, object>();
                para["bizDataNo"] = dtContainer.Rows[0]["mfgordername"].ToString();//生产订单号
                para["docNo"] = ""; //业务流水号
                para["batchNum"] = dtContainer.Rows[0]["containername"].ToString();//批次号
                para["serialCode"] = dtContainer.Rows[0]["containername"].ToString();//序列号
                para["itemCode"] = dtContainer.Rows[0]["materialcode"].ToString();//物料编码
                para["qty"] = Convert.ToInt32(dtContainer.Rows[0]["qty"].ToString());//数量
                para["status"] = "撤销入库";//状态

                string json = JsonConvert.SerializeObject(para);

                string ToAppID_WMS = ConfigurationManager.AppSettings["ToAppID_WMS"];

                //3.保存入库撤销记录
                string insertSql = @"INSERT INTO sync_sendto_wms(methodname,json,toappid,tablename,uniquecolname,uniquecolvalue,create_emp) 
                    VALUES('入库撤销','{0}','{1}','container','containerid','{2}','{3}')";

                insertSql = String.Format(insertSql, json, ToAppID_WMS, dr["containerid"].ToString(), obj["employeeid"].ToString());
                DatabaseHelper.ExecuteSql(insertSql);
            }

        }

        Result r = new Result();
        r.data = true;
        r.total = Convert.ToInt32(0);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}